<?php
/**
 * Internal request abstract class
 * @package WKernel
 */
abstract class WK_IRequest_Abstract {
	protected $params;
	protected $status;
	protected $result;
	
	protected $querystr;
	
	const STATUS_UNDEFINED = -1;
	const STATUS_OK     = 0;
	const STATUS_FAILED = 1;
	const STATUS_EMPTY  = 2;
	
	public function __construct($query_string, $params = array()){		
		$this->status   = self::STATUS_UNDEFINED;
		$this->querystr = $query_string;
		$this->params   = $params;
	}
	
	public function setParameter($name, $value){
		$this->params[$name] = $value;
	}
	
	/**
	 * Return request result
	 * @return WK_Data
	 */
	public function getResult(){
		return $this->result;
	}
	
	/**
	 * Return request status
	 * @return integer
	 */
	public function getStatus(){
		return $this->status;
	}
	
	/**
	 * Check is result empty
	 * @return boolean
	 */
	public function isEmptyResult(){
		if(!$this->result instanceof WK_Data_Abstract || !$this->result->isEmpty()) 
			return true;
		else 
			return false;
	}
	
	/**
	 * Execute request
	 * 
	 */
	public function run() {
		try {
			$this->__run();
			if($this->status == self::STATUS_UNDEFINED){
				if($this->isEmptyResult())
					$this->status = self::STATUS_EMPTY;
				else 
					$this->status = self::STATUS_OK;
			}
		}
		catch(Exception $e){
			$this->status = self::STATUS_FAILED;
			$this->err2res($e->getCode(), $e->getMessage());
		}
	}
	
	/**
	 * Place error into result
	 * @param integer $code
	 * @param string $message
	 */
	protected function err2res($code, $message){
		$this->result = new WK_Data_Map();
		$this->result->newValue('error', array('code' => $code, 'mesage' => $message));
	}	
	
	/**
	 * @return boolean
	 */
	public function isFailed(){
		return $this->status == self::STATUS_FAILED;
	}
	
	/**
	 * @return boolean
	 */
	public function isEmpty(){
		return $this->status == self::STATUS_EMPTY;
	}
	
	/**
	 * @return boolean
	 */
	public function isOk(){
		return $this->status == self::STATUS_OK;
	}
	
	/**
	 * 
	 * Realisation of request parsing and execution
	 */
	abstract protected function __run();
}